from django.conf import settings


def init_permission(request, current_user):
    permission_queryset = current_user.roles.filter(permissions__isnull=False).values('permissions__id',
                                                                                      'permissions__title',
                                                                                      'permissions__menu__id',
                                                                                      'permissions__menu__title',
                                                                                      'permissions__menu__icon',
                                                                                      'permissions__title',
                                                                                      'permissions__pid__title',
                                                                                      'permissions__pid__url',
                                                                                      'permissions__pid',
                                                                                      'permissions__name',
                                                                                      'permissions__url').distinct()

    permission_dict = {}
    menu_dict = {}
    for item in permission_queryset:
        permission_dict[item['permissions__name']] = {
            'id': item['permissions__id'],
            'url': item['permissions__url'],
            'pid': item['permissions__pid'],
            'title': item['permissions__title'],
            'p_title': item['permissions__pid__title'],
            'p_url': item['permissions__pid__url']
        }
        menu_id = item['permissions__menu__id']
        if not menu_id:
            continue
        node = {'id': item['permissions__id'], 'title': item['permissions__title'], 'url': item['permissions__url']}
        if menu_id in menu_dict:
            menu_dict[menu_id]['children'].append(node)
        else:
            menu_dict[menu_id] = {
                'title': item['permissions__menu__title'],
                'icon': item['permissions__menu__icon'],
                'children': [node, ]
            }

    request.session[settings.MOBILEDJ_PERMISSION_SESSION_KEY] = permission_dict
    request.session[settings.MOBILEDJ_MENU_SESSION_KEY] = menu_dict
